package com.etc.order.consumer.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.etc.order.common.domain.SellerInfo;
import com.etc.order.common.dto.SimpleDTO;
import com.etc.order.common.service.SellerInfoService;
import com.etc.order.consumer.filter.AuthFilter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
public class LoginController {
    @Resource
    @Reference
    private SellerInfoService sellerInfoService;

    @GetMapping("/login.html")
    public String loginPage() {
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public SimpleDTO login(String uid, String password) {
        if (sellerInfoService.login(uid, password)) {
            AuthFilter.getSession().setAttribute("userInfo", sellerInfoService.getOne(uid));
            return new SimpleDTO(0, "成功", null);
        } else {
            return new SimpleDTO(1, "用户名或密码不正确", null);
        }
    }

    @GetMapping("/sell/currentUsername")
    @ResponseBody
    public SimpleDTO currentUsername() {
        if (AuthFilter.getSession().getAttribute("userInfo") != null) {
            return new SimpleDTO(0, "成功", ((SellerInfo)AuthFilter.getSession().getAttribute("userInfo")).getUsername());
        } else {
            return new SimpleDTO(1, "获取用户名失败，也许没有登录？", null);
        }
    }
}
